package avl.sv.shared.model.featureGenerator.jocl;

import avl.sv.shared.AVM_Properties;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Properties;
import javax.swing.DefaultComboBoxModel;
import javax.swing.table.DefaultTableModel;
import org.jocl.CL;
import org.jocl.Pointer;
import org.jocl.cl_device_id;
import org.jocl.cl_platform_id;

public final class JOCL_Configure extends javax.swing.JFrame {
    private static final String PlatformNameKey = "CL platform name";
    private static final String DeviceNameKey = "CL device name";
    
    public int getSelectedDeviceIdx(){
        int temp = jComboBoxDevice.getSelectedIndex();
        if (temp < 0){
            temp = 0;
        }
        return temp;
    }
    public int getSelectedPlatformIdx(){
        int temp =  jComboBoxPlatform.getSelectedIndex();
        if (temp < 0){
            temp = 0;
        }
        return temp;       
    }
    
    public JOCL_Configure() {
        initComponents();

        ArrayList<Platform> platforms = getPlatforms();
        DefaultComboBoxModel<Platform> model = new DefaultComboBoxModel<>();
        for (Platform platform:platforms){
            model.addElement(platform);
        }
        jComboBoxPlatform.setModel(model);
        jComboBoxPlatform.setSelectedIndex(0);
        
        Properties p = AVM_Properties.getProperties();
        String platformName = p.getProperty(PlatformNameKey);
        String deviceName = p.getProperty(DeviceNameKey);
        
        for (Platform platform:platforms){
            if (platform.platformName.equals(platformName)){
                jComboBoxPlatform.getModel().setSelectedItem(platform);
                for (Device device:platform.devices){
                    if (device.deviceName.equals(deviceName)){
                        jComboBoxDevice.getModel().setSelectedItem(device);
                    }
                }
            }
        }
         
    }
    
    private class Device {
        final cl_device_id device_Id;
        final String deviceName;

        public Device(cl_device_id device_Id) {
            this.device_Id = device_Id;
            deviceName = getDeviceName(device_Id);
        }
        
        private String getDeviceName(cl_device_id deviceID){
            int param_value_size = 100;
            byte param_value[] = new byte[param_value_size];
            long param_value_size_ret[] = new long[1];
            CL.clGetDeviceInfo(deviceID, CL.CL_DEVICE_NAME, param_value_size, Pointer.to(param_value), param_value_size_ret);
            return new String(param_value);
        }

        @Override
        public String toString() {
            return deviceName;
        }
        
    }
    
    private class Platform {
        final private cl_platform_id platformID;
        final private String platformName;
        final private long deviceType = CL.CL_DEVICE_TYPE_ALL;
        final ArrayList<Device> devices;

        public Platform(cl_platform_id platformID) {
            this.platformID = platformID;
            platformName = getPlatformName(platformID);
            
            // Obtain the number of devices for the platform
            int numDevicesArray[] = new int[1];
            CL.clGetDeviceIDs(platformID, deviceType, 0, null, numDevicesArray);
            int numDevices = numDevicesArray[0];
            
            devices = new ArrayList<>(numDevices);
            cl_device_id device_Ids[] = new cl_device_id[numDevices];
            CL.clGetDeviceIDs(platformID, deviceType, numDevices, device_Ids, null);
            for (int i = 0; i < numDevices; i++){
                cl_device_id deviceID = device_Ids[i];  
                devices.add(new Device(deviceID));
            }

        }
                
        private String getPlatformName(cl_platform_id platformID){
            int param_value_size = 100;
            byte param_value[] = new byte[param_value_size];
            long param_value_size_ret[] = new long[1];
            CL.clGetPlatformInfo(platformID, CL.CL_PLATFORM_NAME, param_value_size, Pointer.to(param_value), param_value_size_ret);
            return new String(param_value);
        }

        @Override
        public String toString() {
            return platformName;
        }
        
        
        
    }

    private ArrayList<Platform> getPlatforms() {
        int num_entries = 10;
        cl_platform_id platforms_Ids[] = new cl_platform_id[num_entries];
        int num_platforms[] = new int[1];
        CL.clGetPlatformIDs(num_entries, platforms_Ids, num_platforms);
        ArrayList<Platform> platforms = new ArrayList<>();
        for (int i = 0; i < num_platforms[0]; i++) {
            Platform platform = new Platform(platforms_Ids[i]);
            platforms.add(platform);
        }
        return platforms;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jComboBoxPlatform = new javax.swing.JComboBox<Platform>();
        jLabel1 = new javax.swing.JLabel();
        jComboBoxDevice = new javax.swing.JComboBox<Device>();
        jLabel2 = new javax.swing.JLabel();
        jButtonAccept = new javax.swing.JButton();
        jButtonCancel = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jComboBoxPlatform.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxPlatformActionPerformed(evt);
            }
        });

        jLabel1.setText("Platform");

        jComboBoxDevice.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxDeviceActionPerformed(evt);
            }
        });

        jLabel2.setText("Device");

        jButtonAccept.setText("Accept");
        jButtonAccept.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAcceptActionPerformed(evt);
            }
        });

        jButtonCancel.setText("Cancel");
        jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 458, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jComboBoxPlatform, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jComboBoxDevice, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButtonCancel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonAccept)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBoxPlatform, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBoxDevice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonAccept)
                    .addComponent(jButtonCancel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jComboBoxPlatformActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxPlatformActionPerformed
        Platform platform = (Platform) jComboBoxPlatform.getModel().getSelectedItem();
        DefaultComboBoxModel<Device> model = new DefaultComboBoxModel<>();
        for (Device device:platform.devices){
            model.addElement(device);
        }
        jComboBoxDevice.setModel(model);
        jComboBoxDevice.setSelectedIndex(0);
    }//GEN-LAST:event_jComboBoxPlatformActionPerformed

    private void jComboBoxDeviceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxDeviceActionPerformed
        Device device = (Device) jComboBoxDevice.getSelectedItem();        
        DefaultTableModel model = new DefaultTableModel();
        model.addColumn("Parameter");
        model.addColumn("Value");
        model.addRow(new Object[]{"CL_DEVICE_VENDOR", getString(device, CL.CL_DEVICE_VENDOR)});
        model.addRow(new Object[]{"CL_DEVICE_VERSION", getString(device, CL.CL_DEVICE_VERSION)});
        model.addRow(new Object[]{"CL_DRIVER_VERSION", getString(device, CL.CL_DRIVER_VERSION)});
        model.addRow(new Object[]{"CL_DEVICE_GLOBAL_MEM_SIZE", String.valueOf(Math.round(getMemoryTotal(device)/Math.pow(2, 30)*10)/10)+" GB"});
        model.addRow(new Object[]{"CL.CL_DEVICE_LOCAL_MEM_SIZE", String.valueOf(getIntParam(device, CL.CL_DEVICE_LOCAL_MEM_SIZE)/Math.pow(2, 10)+ " KB")});
        model.addRow(new Object[]{"CL_DEVICE_MAX_CLOCK_FREQUENCY", String.valueOf(getIntParam(device, CL.CL_DEVICE_MAX_CLOCK_FREQUENCY)+ " MHz")});
        model.addRow(new Object[]{"CL_DEVICE_MAX_COMPUTE_UNITS", String.valueOf(getIntParam(device, CL.CL_DEVICE_MAX_COMPUTE_UNITS))});
        model.addRow(new Object[]{"CL_DEVICE_MAX_MEM_ALLOC_SIZE", String.valueOf(getLongParam(device, CL.CL_DEVICE_MAX_MEM_ALLOC_SIZE)/Math.pow(2, 10)+ " KB")});
        model.addRow(new Object[]{"CL_DEVICE_MAX_PARAMETER_SIZE", String.valueOf(getLongParam(device, CL.CL_DEVICE_MAX_PARAMETER_SIZE)/Math.pow(2, 10)+ " KB")});
        model.addRow(new Object[]{"CL_DEVICE_MAX_WORK_GROUP_SIZE", String.valueOf(getIntParam(device, CL.CL_DEVICE_MAX_WORK_GROUP_SIZE))});
        jTable1.setModel(model);
    }//GEN-LAST:event_jComboBoxDeviceActionPerformed

    private String getString(Device device, int paramID){
        int param_value_size = 200;
        byte buffer[] = new byte[param_value_size];
        long param_value_size_ret[] = new long[1];
        CL.clGetDeviceInfo(device.device_Id, paramID, param_value_size, Pointer.to(buffer), param_value_size_ret);
        return new String(buffer);
    }
    
    private long getLongParam(Device device, int paramID){
        int param_value_size = 8;
        byte buffer[] = new byte[param_value_size];
        long param_value_size_ret[] = new long[1];
        CL.clGetDeviceInfo(device.device_Id, paramID, param_value_size, Pointer.to(buffer), param_value_size_ret);
        return ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).getLong();
    }
    
    private int getIntParam(Device device, int paramID){
        int param_value_size = 8;
        byte buffer[] = new byte[param_value_size];
        long param_value_size_ret[] = new long[1];
        CL.clGetDeviceInfo(device.device_Id, paramID, param_value_size, Pointer.to(buffer), param_value_size_ret);
        return ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).getInt();
    }
    
    private long getMemoryTotal(Device device){
        int param_value_size = 8;
        byte buffer[] = new byte[param_value_size];
        long param_value_size_ret[] = new long[1];
        CL.clGetDeviceInfo(device.device_Id, CL.CL_DEVICE_GLOBAL_MEM_SIZE, param_value_size, Pointer.to(buffer), param_value_size_ret);
        return ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).getLong();
    }
    
    public long getMemoryTotal(){
        Device device = (Device) jComboBoxDevice.getSelectedItem();
        int param_value_size = 8;
        byte buffer[] = new byte[param_value_size];
        long param_value_size_ret[] = new long[1];
        CL.clGetDeviceInfo(device.device_Id, CL.CL_DEVICE_GLOBAL_MEM_SIZE, param_value_size, Pointer.to(buffer), param_value_size_ret);
        return ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).getLong();
    }
    
    private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed
        dispose();
    }//GEN-LAST:event_jButtonCancelActionPerformed

    private void jButtonAcceptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAcceptActionPerformed
        Properties p = AVM_Properties.getProperties();
        String platformName = jComboBoxPlatform.getSelectedItem().toString();
        String deviceName = jComboBoxDevice.getSelectedItem().toString();
        p.setProperty(PlatformNameKey, platformName);
        p.setProperty(DeviceNameKey, deviceName);
        AVM_Properties.setProperties(p);
        dispose();
    }//GEN-LAST:event_jButtonAcceptActionPerformed

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(JOCL_Configure.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(JOCL_Configure.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(JOCL_Configure.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(JOCL_Configure.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new JOCL_Configure().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAccept;
    private javax.swing.JButton jButtonCancel;
    private javax.swing.JComboBox<Device> jComboBoxDevice;
    private javax.swing.JComboBox<Platform> jComboBoxPlatform;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
